package com.jbp.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.dao.ArticleCommentDao;
import com.jbp.exception.RRException;
import com.jbp.model.*;
import com.jbp.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jbp.utils.PageUtils;
import com.jbp.utils.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 动态评论(ArticleComment)表服务实现类
 * @author cc
 * @since 2020-08-25 14:37:34
 */
@Service
public class ArticleCommentServiceImpl extends ServiceImpl<ArticleCommentDao, ArticleComment> implements ArticleCommentService {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private UserService userService;
    @Autowired
    private ArticleCommentLikeService articleCommentLikeService;
    @Autowired
    private ArticleCommentCommentService articleCommentCommentService;
    @Autowired
    private TecentMsgService tecentMsgService;
    @Autowired
    private KeywordService keywordService;
    @Autowired
    private UserLevelService userLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<ArticleComment> queryWrapper = new QueryWrapper<>();
        if (params.get("articleId") == null){
            throw new RRException("动态id不能为空");
        }
        queryWrapper.eq("article_id",params.get("articleId"));
        queryWrapper.eq("status","normal");
        queryWrapper.orderByDesc("update_time");
        IPage<ArticleComment> page = this.page(
                new Query<ArticleComment>().getPage(params),
                queryWrapper
        );

        for (ArticleComment articleComment : page.getRecords()) {
            User reader = userService.getById(articleComment.getReaderId());
            if (reader!=null) {
                articleComment.setReaderName(reader.getName());
                articleComment.setReaderImg(reader.getImg());
                articleComment.setReaderSex(reader.getSex());
                articleComment.setReaderLevel(reader.getLevel());
                articleComment.setReaderLevelOn(userLevelService.levelOn(reader.getId()));
            }
            articleComment.setContent(keywordService.replaceKeyWord(articleComment.getContent()));

            //是否点赞
            ArticleCommentLike articleCommentLike = articleCommentLikeService.getOne(new QueryWrapper<ArticleCommentLike>()
                    .eq("comment_id", articleComment.getId())
                    .eq("reader_id", articleComment.getReaderId())
            );
            articleComment.setLiked(articleCommentLike!=null && articleCommentLike.getId()==1);

            //获取第一条评论
            ArticleCommentComment articleCommentComment = articleCommentCommentService.getOne(new QueryWrapper<ArticleCommentComment>()
                    .eq("comment_id", articleComment.getId())
                    .eq("status","normal")
                    .orderByDesc("update_time")
                    .last("limit 1")
            );
            if (articleCommentComment!=null) {
                if (articleCommentComment.getReplyUserId()!=null) {
                    User reply = userService.getById(articleCommentComment.getReplyUserId());
                    articleCommentComment.setReplyUserName(reply.getName());
                }
                if (articleCommentComment.getReaderId()!=null) {
                    User u = userService.getById(articleCommentComment.getReaderId());
                    articleCommentComment.setReaderName(u.getName());
                    articleCommentComment.setReaderImg(u.getImg());
                    articleCommentComment.setReaderSex(u.getSex());
                    articleCommentComment.setReaderLevel(u.getLevel());
                    articleCommentComment.setReaderLevelOn(userLevelService.levelOn(u.getId()));
                    articleCommentComment.setContent(keywordService.replaceKeyWord(articleCommentComment.getContent()));
                }
            }
            articleComment.setArticleCommentComment(articleCommentComment);
        }
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void add(ArticleComment articleComment) {
        Article article = articleService.getById(articleComment.getArticleId());
        if (article==null) {
            throw new RRException("动态id不能为空");
        }
        save(articleComment);

        article.setCommentCount(article.getCommentCount()+1);
        articleService.updateById(article);

        User reader = userService.getById(articleComment.getReaderId());
        if (reader!=null) {
            articleComment.setReaderName(reader.getName());
            articleComment.setReaderImg(reader.getImg());
            articleComment.setReaderSex(reader.getSex());
            articleComment.setReaderLevel(reader.getLevel());
            articleComment.setReaderLevelOn(userLevelService.levelOn(reader.getId()));
        }
        articleComment.setLikeCount(0);
        articleComment.setCommentCount(0);
        articleComment.setCreateTime(new Date());

        if (!articleComment.getReaderId().equals(article.getAuthorId())) {
            new Thread(){
                @Override
                public void run() {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("msg", "评论了你的动态");
                    map.put("reader", userService.getById(articleComment.getReaderId()));
                    map.put("comment", articleComment.getContent());
                    map.put("article", articleService.getArticleById(article.getAuthorId(), article.getId()));

                    tecentMsgService.sendMsgFromManger("article", article.getAuthorId().toString(), JSON.toJSONString(map));
                }
            }.start();
        }
    }

    @Override
    @Transactional
    public void remove(Integer articleCommentId) {
        ArticleComment articleComment = getById(articleCommentId);
        if (articleComment != null)  {
            articleComment.setStatus("del");
            updateById(articleComment);
        }
        Article article = articleService.getById(articleComment.getArticleId());
        if (article==null) {
            throw new RRException("动态id不能为空");
        }
        int l = article.getCommentCount()-1;
        article.setCommentCount(l<0 ? 0 : l);
        articleService.updateById(article);
    }
}